﻿package Welsy4.Connect.commands
{
	import com.adobe.cairngorm.commands.SequenceCommand;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.IResponder;
	import mx.controls.Alert;
	
	import com.adobe.cairngorm.commands.Command;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	
	import Welsy4.Connect.business.CreateUserDelegate;
	import Welsy4.Connect.events.UserEvent;
	import Welsy4.Connect.events.ResponseEvent;
	import Welsy4.Connect.events.ChainEvent;
	import Welsy4.Connect.model.ConnectModel;
	import Welsy4.Connect.vo.HttpServiceHandler;
	import Welsy4.Connect.vo.User;
	/**
	 * ...
	 * @author DefaultUser (Tools -> Custom Arguments...)
	 */
	public class CreateUserCommand extends SequenceCommand implements Command, IResponder
	{
		
		public function CreateUserCommand() 
		{
			
		}
		override public function execute(event:CairngormEvent):void {
			this.nextEvent = ChainEvent(event).nextChainedEvent;
			
			var createUserDelegate : CreateUserDelegate = new CreateUserDelegate(this);
			var userEvent : UserEvent = UserEvent (event);
			createUserDelegate.CreateNewUser(userEvent.user);
			Alert.show("Creating user " + userEvent.user.nickname); 
			ConnectModel.getInstance().addQueue("CreateUserCommand.execute");
		}
		
		public function result(event:Object):void {
		    ConnectModel.getInstance().addQueue("CreateUserCommand.result");
			
			ConnectModel.getInstance().httpServiceHandler = new HttpServiceHandler();
			ConnectModel.getInstance().httpServiceHandler.setXML(event.result);
			
			
			
			
			if (ConnectModel.getInstance().httpServiceHandler.getResultStatus() == ConnectModel.SESSION_OK) {
			    	
				    Alert.show(ConnectModel.getInstance().httpServiceHandler.xml + "\n\nUSER created!!!" + "\n\n" + event.result);
					// dispatchevent user has been created --> a new command for a new era
					ConnectModel.getInstance().lastUserFound = new User(ConnectModel.getInstance().httpServiceHandler.xml.principal.login);
					ConnectModel.getInstance().lastUserFound.principal_id = ConnectModel.getInstance().httpServiceHandler.xml.principal.attribute("principal-id");
					this.executeNextCommand();
					
			} else {
				
			    CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.INVALID, event.result));
			}
			
		}
		
		public function fault(event:Object):void {
			ConnectModel.getInstance().addQueue("CreateUserCommand.fault");
		}
	}
	
}